<template>
  <div>
    <div class="top">
      <i class="el-icon-menu"></i>
      <span>收银</span>
    </div>
    <hr style="color: grey" />
    <div class="content">
      <div class="content_top">
        <el-input
          v-model="input"
          placeholder="请输入商品条码或扫码"
          :readonly="!checked"
          style="width: 300px"
          @keyup.enter.native="search(1)"
        ></el-input>
        <el-input
          v-model="input3"
          placeholder="请输入商品条码或扫码"
          class="hide"
          ref="input"
          style="width: 300px"
          @keyup.enter.native="search(2)"
        ></el-input>
        <el-button :disabled="!checked" @click="search(1)">查询</el-button>
        <el-checkbox v-model="checked" @change="danxuan()"
          >手动输入条形码</el-checkbox
        >
      </div>
      <div class="content_center">
        <div class="name">收银员&nbsp;&nbsp;&nbsp;{{ name }}</div>
        <div class="date">
          日期&nbsp;&nbsp;&nbsp;{{ date | dateFormate(1) }}
        </div>
        <div class="liushuihao" v-if="false">
          流水号&nbsp;&nbsp;&nbsp;31321321321321
        </div>
      </div>
      <div class="content_bottom">
        <div class="content_bottom_table">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            max-height="500px"
          >
            <el-table-column type="index" width="50" align="center">
            </el-table-column>
            <el-table-column prop="goods_name" label="商品名称" align="center">
            </el-table-column>
            <el-table-column prop="goods_price" label="单价" align="center">
            </el-table-column>
            <el-table-column prop="order_count" label="数量" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.order_count"
                  @change="handleChange"
                  :min="1"
                  size="small"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="activity_discount" label="活动" align="center">
              <template slot-scope="scope">
                {{
                  scope.row.activity_discount==1?"买一送一":(scope.row.activity_discount==0?"原价":scope.row.activity_discount*10+"折")
                }}
              </template>
            </el-table-column>
            <el-table-column prop="summoney" label="金额" align="center">
              <template slot-scope="scope">
                {{
                  (scope.row.summoney =(scope.row.activity_discount==0?scope.row.goods_price * scope.row.order_count:scope.row.goods_price * scope.row.order_count*scope.row.activity_discount)
                    ) | keepTwoNum
                }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  @click="handleClick(scope.$index, scope.row)"
                  type="text"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <span style="float: right">总计:&nbsp;{{ allmoney }}元</span>
        </div>
        <div class="content_bottom_button">
          <el-button style="width: 100%" @click="jujiao2()">结账</el-button>
        </div>
      </div>
      <el-dialog
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose"
      >
        <h3 style="padding-bottom: 10px">结账信息</h3>
        <hr />
        <div class="dialog" id="daying">
          <div class="neitable">
            <span
              >收银员&nbsp;&nbsp;&nbsp;{{
                name
              }}&nbsp;&nbsp;&nbsp;日期&nbsp;&nbsp;&nbsp;{{
                date | dateFormate(1)
              }}&nbsp;&nbsp;&nbsp;流水号&nbsp;&nbsp;&nbsp;{{
                date | dateFormate(2)
              }}</span
            >
            <el-table :data="tableData" style="width: 100%">
              <el-table-column
                prop="goods_name"
                label="商品名称"
                align="center"
              >
              </el-table-column>
              <el-table-column prop="goods_price" label="单价" align="center">
              </el-table-column>
              <el-table-column prop="order_count" label="数量" align="center">
              </el-table-column>
              <el-table-column prop="activity_discount" label="活动" align="center">
                <template slot-scope="scope">
                {{
                  scope.row.activity_discount==1?"买一送一":(scope.row.activity_discount==0?"原价":scope.row.activity_discount*10+"折")
                }}
              </template>
              </el-table-column>
              <el-table-column prop="summoney" label="金额" align="center">
                <template slot-scope="scope">
                  {{
                    (scope.row.summoney =
                      scope.row.activity_discount==0?scope.row.goods_price * scope.row.order_count:scope.row.goods_price * scope.row.order_count*scope.row.activity_discount)
                      | keepTwoNum
                  }}
                </template>
              </el-table-column>
            </el-table>
            <span style="float: right">总计:&nbsp;{{ allmoney }}元</span>
          </div>
          <div class="fukuan">
            <div class="shihsou">
              <b>实收&nbsp;&nbsp;&nbsp;</b
              ><el-input
                v-model="input2"
                ref="input2"
                style="width: 150px"
                onkeyup="value=value.replace(/[^\d&\.]/g,'')"
                @keyup.enter.native="queren()"
              ></el-input>
            </div>
            <div class="zhaoling">
              <b>找零</b
              ><span class="zhaoling_span">{{ zhaoling.toFixed(2) }}</span>
            </div>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="queren()">确定收银</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :visible.sync="dialogVisible2"
        width="20%"
        :before-close="handleClose2"
      >
        <el-button
          class="piaoju"
          type="primary"
          @click="
            (dialogVisible2 = false),
              (dialogVisible = false),
              checked ? true : dingshiqi(),
              tianjia()
          "
          style="width: 150px"
          v-print="'#daying'"
          >打印票据</el-button
        >
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import stroe from "../store/index";
export default {
  name: "cash",
  data() {
    return {
      checked: false,
      name: "",
      num: "",
      id: "",
      input: "",
      input2: "",
      input3: "",
      discount:'',
      timer: "",
      date: new Date(),
      dialogVisible: false,
      dialogVisible2: false,
      tableData: [],
      tableData2: [],
      // goods: {
      //   goods_amount: "",
      //   goods_bar_code: "",
      //   goods_id: "",
      //   goods_name: "",
      //   goods_price: "",
      //   order_count: 1,
      //   summoney: 0,
      // },
    };
  },
  filters: {
    keepTwoNum(value) {
      value = Number(value);
      return value.toFixed(2);
    },
    dateFormate(dateStr, num) {
      let dt = new Date(dateStr);
      let y = dt.getFullYear();
      let m = (dt.getMonth() + 1).toString().padStart(2, "0");
      let d = dt.getDate().toString().padStart(2, "0");
      let hh = dt.getHours().toString().padStart(2, "0");
      let mm = dt.getMinutes().toString().padStart(2, "0");
      if (num == 1) {
        return `${y}-${m}-${d} ${hh}:${mm}`;
      } else if (num == 2) {
        return `${y}${m}${d}${hh}${mm}000000`;
      }
    },
  },
  methods: {
    riqi(dateStr) {
      let dt = new Date(dateStr);
      let y = dt.getFullYear();
      let m = (dt.getMonth() + 1).toString().padStart(2, "0");
      let d = dt.getDate().toString().padStart(2, "0");
      let hh = dt.getHours().toString().padStart(2, "0");
      let mm = dt.getMinutes().toString().padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}`;
    },
    danxuan() {
      if (this.checked) {
        clearInterval(this.timer);
        this.input = "";
      } else {
        this.input3 = "";
        this.jujiao();
      }
    },
    jujiao() {
      //console.log(123);
      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },
    jujiao2() {
      if (this.tableData.length > 0) {
        this.dialogVisible = true;
        this.date = new Date();
        clearInterval(this.timer);
        this.$nextTick(() => {
          this.$refs.input2.focus();
        });
        this.input2 = "";
      } else {
        this.$message("还没有商品");
      }
    },
    dingshiqi() {
      this.timer = setInterval(() => {
        this.jujiao();
      }, 1000);
    },
    search(index) {
      if (index == 1) {
        if (this.input != "") {
          if (!/^\d+$/.test(this.input)) {
            this.$message("商品条码错误，请重新输入！");
            this.input = "";
          } else {
            axios
              .get("/user/order_select_good", {
                params: {
                  order_bar_code: this.input,
                },
              })
              .then((response) => {
                console.log(111, response);
                if (response.data.code == 200||response.data.code == 201) {
                  response.data.data.order_count = 1;
                  response.data.data.summoney = 0;
                  response.data.data.order_id = 0;
                  for (
                    let index = 0, len = this.tableData.length;
                    index < len;
                    index++
                  ) {
                    if (
                      response.data.data.goods_id ==
                      this.tableData[index].goods_id
                    ) {
                      this.tableData[index].order_count++;
                      break;
                    } else {
                      if (index == len - 1)
                        this.tableData.push(response.data.data);
                    }
                  }
                  if (this.tableData.length == 0) {
                    this.tableData.push(response.data.data);
                  }
                  this.input = "";
                }else if(response.data.code == 500){
                  this.$message("没有该商品，请重新输入！");
                  this.input = "";
                }
              })
              .catch((error) => {
                console.log(error);
              });
          }
        } else {
          this.$message("商品条码不能为空！");
        }
      } else if (index == 2) {
        if (!/^\d+$/.test(this.input3)) {
          this.$message("商品条码错误，请重新输入！");
          this.input3 = "";
        } else {
          
          axios
            .get("/user/order_select_good", {
              params: {
                order_bar_code: this.input3,
              },
            })
            .then((response) => {
              console.log(222, response);
              if (response.data.code == 200||response.data.code == 201) {
                response.data.data.order_count = 1;
                response.data.data.summoney = 0;
                response.data.data.order_id = 0;
                for (
                  let index = 0, len = this.tableData.length;
                  index < len;
                  index++
                ) {
                  if (
                    response.data.data.goods_id ==
                    this.tableData[index].goods_id
                  ) {
                    this.tableData[index].order_count++;
                    break;
                  } else {
                    if (index == len - 1)
                      this.tableData.push(response.data.data);
                  }
                }
                if (this.tableData.length == 0) {
                  this.tableData.push(response.data.data);
                }
                this.input = this.input3;
                this.input3 = "";
              }else if(response.data.code == 500){
                  this.$message("没有该商品，请重新输入！");
                  this.input3 = "";
              }
            })
            .catch((error) => {
              console.log(error);
            });
        }
      }else {
          this.$message("商品条码不能为空！");
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
          if (!this.checked) {
            this.dingshiqi();
          }
        })
        .catch(() => {});
    },
    handleClose2(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    queren() {
      if (this.zhaoling >= 0) {
        this.dialogVisible2 = true;
      } else {
        this.$message("钱不够");
      }
    },
    tianjia() {
      console.log("employee_id", this.id);
      console.log("order_num", this.allnumber);
      console.log("order_total_price", this.allmoney);
      this.tableData2 = this.tableData;
      console.log(this.tableData2);
      for (let index = 0, len = this.tableData2.length; index < len; index++) {
        delete this.tableData2[index].goods_price;
      }
      console.log("orderInfoVoList", this.tableData2);
      let dat = this.riqi(this.date);
      console.log("order_date", dat);
      axios
        .post("/user/add_order", {
          employee_id: this.id,
          order_date: dat,
          orderInfoVoList: this.tableData2,
          order_num: this.allnumber,
          order_total_price: parseFloat(this.allmoney),
        })
        .then((response) => {
          console.log(response);
          this.tableData=[]
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleClick(index, row) {
      console.log(index, row);
      this.tableData.splice(index, 1);
    },
    handleChange(value) {
      console.log(value);
    },
  },
  computed: {
    allmoney() {
      return this.tableData 
        .map((row) => row.activity_discount==0?row.goods_price * row.order_count:row.goods_price * row.order_count*row.activity_discount)
        .reduce((acc, cur) => parseFloat(cur) + acc, 0)
        .toFixed(2);
    },
    allnumber() {
      return this.tableData
        .map((row) => row.order_count)
        .reduce((acc, cur) => parseFloat(cur) + acc, 0);
    },
    zhaoling() {
      if (this.input2 == "") {
        return 0 - this.allmoney;
      }
      return parseFloat(this.input2) - this.allmoney;
    },
  },
  mounted() {
    this.dingshiqi();
    this.name = stroe.state.user.name;
    this.num = stroe.state.user.num;
    this.id = stroe.state.user.id;
  },
  created() {},
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style scoped>
.top i {
  font-size: 24px;
  margin-right: 10px;
}
.top span {
  font-size: 16px;
}
.top {
  margin-bottom: 10px;
}

.content {
  margin-top: 10px;
  width: 100%;
  height: 700px;
  border-radius: 3px;
  background-color: #eee;
}
.content_top {
  width: 80%;
  height: 80px;
  margin: 0 auto;
  padding: 20px 0;
  box-sizing: border-box;
}
.content_top .el-input,
.content_top .el-button {
  margin-right: 20px;
}
.hide {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
.content_center {
  width: 80%;
  height: 20px;
  margin: 0 auto;
}
.name {
  float: left;
  margin-left: 10px;
}
.date {
  float: right;
  margin-right: 50%;
}
.liushuihao {
  float: right;
  margin-right: 10%;
}
.content_bottom {
  width: 80%;
  height: 100%;
  margin: 10px auto;
}
.content_bottom_table {
  width: 75%;
  height: 100%;
  float: left;
}
.content_bottom_table .el-table {
  border-radius: 5px;
}
.content_bottom_button {
  width: 20%;
  float: right;
}

.neitable {
  width: 70%;
  margin-top: 10px;
}
.fukuan {
  width: 25%;
  position: absolute;
  top: 100px;
  right: 10px;
}

.zhaoling {
  margin-top: 30px;
}
.zhaoling_span {
  margin-left: 60px;
}
.piaoju {
  margin-left: 30%;
}
</style>